<?php

/**
 * This is the model class for table "b2b_order_tuan".
 *
 * The followings are the available columns in table 'b2b_order_tuan':
 * @property integer $id
 * @property string $b2b_order_id
 * @property string $order_time
 * @property integer $center_id
 * @property integer $order_count
 * @property integer $order_realcount
 * @property string $customer_company
 * @property integer $sub_center_id
 * @property string $sub_center_name
 * @property string $create_at
 * @property string $update_at
 */
class B2bOrderTuan extends CActiveRecord {
    
    const TUAN_NEW = 1;
    const TUAN_CANCEL_MSG = 3;
    const TUAN_SUCCESS = 2;
    const TUAN_RE = 4;
    const TUAN_CANCEL = 5;
    const TJ_REPORT = 6;
    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return B2bOrderTuan the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'b2b_order_tuan';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
        //    array('b2b_order_id, order_time, center_id, order_count, order_realcount, customer_company, sub_center_id, sub_center_name', 'required'),
        //    array('id, center_id, order_count, order_realcount, sub_center_id', 'numerical', 'integerOnly' => true),
            array('b2b_order_id', 'length', 'max' => 2000),
            array('customer_company', 'length', 'max' => 128),
            array('sub_center_name', 'length', 'max' => 250),
            array('create_at', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, b2b_order_id, order_time, center_id, order_count, order_realcount, customer_company, sub_center_id, sub_center_name, create_at, update_at', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'ID',
            'b2b_order_id' => 'B2b Order',
            'order_time' => 'Order Time',
            'center_id' => 'Center',
            'order_count' => 'Order Count',
            'order_realcount' => 'Order Realcount',
            'customer_company' => 'Customer Company',
            'sub_center_id' => 'Sub Center',
            'sub_center_name' => 'Sub Center Name',
            'create_at' => 'Create At',
            'update_at' => 'Update At',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search($centerid) {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;        
        $criteria->addCondition("sub_center_id=$centerid");
        $s = $this->statuscode;
        if($this->statuscode == B2bOrderTuan::TUAN_SUCCESS||$this->statuscode == B2bOrderTuan::TJ_REPORT){
            $criteria->addCondition("statuscode=$this->statuscode");
        }else{
            $criteria->addInCondition("statuscode", array(B2bOrderTuan::TUAN_SUCCESS,  B2bOrderTuan::TJ_REPORT));
        }
        if($this->customer_company != ""){
            $criteria->compare('customer_company', $this->customer_company, true);
        }

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
            'pagination' =>array('pageSize'=>30)
        ));
    }

    /**
     * 取消团预约
     * $companyuser 是否为公司用户取消 默认为是 
     */
    public function cancel($order,$companyuser=true) {
        if (!($order instanceof B2bOrderTuan)) {
            throw new Exception("非法的参数");
        }
        if($companyuser&&$order->statuscode != 1 && $order->statuscode != 4) {
            return "此状态下不可取消";
        }elseif(!$companyuser&&$order->statuscode != B2bOrderTuan::TUAN_SUCCESS){
            return "此状态下不可取消";
        }
        $b2borderupdatesql = <<<EOF
update  `marvel`.`b2b_order` set `status`=6
where `id` in ($order->b2b_order_id);
EOF;

        $b2bextusersql = <<<EOF
update  `marvel`.`b2b_external_user` set `statuscode`=0
where `id` in (
   select `ext_user_id` from  `marvel`.`b2b_order`
where `id` in ($order->b2b_order_id) 
   );                    
EOF;
        $b2borderupdat = Yii::app()->db->createCommand($b2borderupdatesql);
        $b2bextuser = Yii::app()->db->createCommand($b2bextusersql);
        $transaction = Yii::app()->db->beginTransaction();
        try {
            //b2border表中所有的用户预约记录全部设为取消预约状态
            $b2borderupdat->execute();
            //ext_user置为可在预约状态
            $b2bextuser->execute();

            $order->statuscode = 5;
            $order->update();
            $transaction->commit();
            return true;
        } catch (Exception $exc) {
            $transaction->rollback();
            return "数据库繁忙，请稍后再试";
        }
    }

    /**
     * 团单通过
     */
    public function procpass($order) {
        if (!($order instanceof B2bOrderTuan)) {
            throw new Exception("非法的参数");
        }
        if ($order->statuscode != 1 && $order->statuscode != 4) {
            return "此状态下不可通过";
        }
        $b2borderupdatesql = <<<EOF
update  `marvel`.`b2b_order` set `status`=2
where `id` in ($order->b2b_order_id);
EOF;

        $b2bextusersql = <<<EOF
update  `marvel`.`b2b_external_user` set `statuscode`=5
where `id` in (
   select `ext_user_id` from  `marvel`.`b2b_order`
where `id` in ($order->b2b_order_id) 
   );                    
EOF;
        $b2borderupdat = Yii::app()->db->createCommand($b2borderupdatesql);
        $b2bextuser = Yii::app()->db->createCommand($b2bextusersql);

        $transaction = Yii::app()->db->beginTransaction();
        try {
            //b2border表中所有的用户预约记录全部设为预约成功状态
            $b2borderupdat->execute();
            $b2bextuser->execute();
            $order->statuscode = 2;
            $order->update();
            $transaction->commit();
            return true;
        } catch (Exception $exc) {
            $transaction->rollback();
            return false;
        }
    }

    /*
     * 获取新团约
     */

    public function getneworder(&$maxid, $subcenterid) {
        $criteria = new CDbCriteria;
        if ($maxid > 0) {
            $criteria->compare("id", ">" . $maxid);
        }
        $criteria->addCondition("sub_center_id=" . $subcenterid);
        $criteria->addInCondition("statuscode", array(1, 4));

        $ret = $this->findAll($criteria);
        $items = array();
        foreach ($ret as $t) {
            if ($t->id > $maxid) {
                $maxid = $t->id;
            }
            $item["id"] = $t->id;
            $item["order_time"] = $t->order_time;
            $item["sub_center_name"] = $t->sub_center_name;
            $item["customer_company"] = $t->customer_company;
            $item["people_count"] = $t->order_count;
            $item["order_type"] = 2; //团单    
            array_push($items, $item);
        }
        return $items;
    }

    /**
     * 更新团单状态
     */
    public function upstatus($id, $centerid, $status) {
        $it = $this->findByAttributes(array("id" => $id, "sub_center_id" => $centerid));
        if (null === $it) {
            return "错误的ID";
        }
        return $this->cancel($it,false);
    }

}